///////////////////////////////////////////////////////////////////////////////
//
//  Alexey Kolonitsky
//  Kolonitsky Developers Aliance (c) 2011
//
///////////////////////////////////////////////////////////////////////////////

package gallery
{

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.display.Sprite;
    import flash.events.ProgressEvent;
    import flash.events.Event;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    import flash.net.URLRequest;
    import flash.system.Security;
    import flash.system.System;
    import flash.system.ApplicationDomain;
    import flash.system.SecurityDomain;
    import flash.system.LoaderContext;

    import org.kolonitsky.alexey.net.XMLService;
    import org.kolonitsky.alexey.net.PicasaRSSService;
    import org.kolonitsky.alexey.debug.DebugWrapper;
    import org.kolonitsky.alexey.net.MultiLoader;
    import org.kolonitsky.alexey.events.MultiLoaderEvent;
    import org.kolonitsky.alexey.events.ListEvent;
    import org.kolonitsky.alexey.collections.IList;

    import control.Picture;

    import caurina.transitions.Tweener;
    
    import ApplicationCreator; ApplicationCreator;

    /**
     *  Most simple preloader.
     */ 
    [Frame(factoryClass="org.kolonitsky.alexey.preloader.Preloader")]
    
    /**
     *  Default settings for swf file
     */ 
    [SWF(backgroundColor="#FFFFFF", frameRate="30")]

    /**
     *  Simple flash gallery. Display images from source. Source is URL flashvar
     */
    public class Gallery extends Sprite
    {

        /**
         *  Availabel services by type
         */
        public var services:Object =
        {
            picasa: PicasaRSSService,
            xml: GalleryXMLService
        }


        //------------------------------
        // Constructor
        //------------------------------

        public function Gallery()
        {
            trace("INFO: Gallery v0.0.2");
            
            addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);

            // Load tweener.
            const LIB_PATH:String = "http://kolonitsky.org/pub/swf/tweener_1.33.74.swf";
            var request:URLRequest = new URLRequest(LIB_PATH);
            var context:LoaderContext = new LoaderContext(true, ApplicationDomain.currentDomain, SecurityDomain.currentDomain);
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeLoadingTweener);
            loader.load(request, context);
        }

        public function completeLoadingTweener(event:Event):void
        {
            trace("INFO: Loaded tweener library.");   
        }




        //-----------------------------------------------------------------------
        //
        // Private logic
        //
        //-----------------------------------------------------------------------

        /**
         *  Array for store all SSS items from struct file.
         */
        private var rssItems:Array /* of Objects */ = [];


        /**
         *  Butch loader load all images.
         */
        private var imageLoader:MultiLoader = null;

        /**
         *
         */
        private var viewer:ImageSlideShow = null;


        /**
         *  Resize handler
         */
        private function layout():void
        {
        }

        /**
         * Create structure loader. Any loader is a XMLService
         */
        private function createService(type:String):XMLService
        {

            if (type == null || type == "" || !(type in services))
               return null;

            var serviceClass:Class = services[type];
            return new serviceClass;
        }


        //----------------------------------------------------------------
        // Event handlers
        //----------------------------------------------------------------

        private function addedToStageHandler(event:Event):void
        {
            // read flashvar url
            var url:String = loaderInfo.parameters.url;
            url = decodeURI(url);

            var type:String = loaderInfo.parameters.type;

            trace("DEBUG: addedToStageHandler \n\turl: " + url + ", \n\ttype: " + type);

            if (url)
            {
                var structLoader:XMLService = createService(type);
                if (structLoader)
                {
                    structLoader.addEventListener(Event.COMPLETE, structLoader_completeHandler);
                    structLoader.load(url);
                }
                else
                {
                    trace("ERROR: unavailabel type");
                }
            }
            else
            {
                trace("ERROR: url flashvar expected. Please specify this parameter.");
            }
            
            stage.align = "TL";
            stage.scaleMode = "noScale";
            
            layout();
            
            stage.addEventListener(Event.RESIZE, resizeHandler);

            function resizeHandler():void
            {
                layout()
            }
        }


        /**
         *  Load RSS handler save all items to rssItems array. Create
         *  multiloader queue and start loading images. Build UI for display
         *  images.
         */
        private function structLoader_completeHandler(event:Event):void
        {
            trace("INFO: structLoader_completeHandler");
            event.currentTarget.removeEventListener(Event.COMPLETE, structLoader_completeHandler);

            var serv:IList = event.currentTarget as IList;

            imageLoader = new MultiLoader(3);
            imageLoader.addEventListener(Event.COMPLETE, imageLoader_completeHandler);
            imageLoader.addEventListener(ProgressEvent.PROGRESS, imageLoader_progressHandler);
            imageLoader.addEventListener(MultiLoaderEvent.PART_LOADED, imageLoader_partLoadedHandler);

            var n:int = serv.length;
            for (var i:int = 0; i < n; i++)
            {
                var item:Object = serv.getItemAt(i);
                DebugWrapper.log("INFO: image " + item.image);

                rssItems.push(item);

                imageLoader.addImage(String(i), item.image);
            }

            if (n)
            {
                DebugWrapper.log("INFO: Strat loading images.");
                imageLoader.start();

                viewer = new ImageSlideShow(true);
                addChild(viewer);
            }
        }

        private function imageLoader_partLoadedHandler(event:MultiLoaderEvent):void
        {
            var index:int = int(event.partId);
            var image:Loader = imageLoader.getBitmap(event.partId);

            DebugWrapper.log("INFO: imageLoader_partLoadedHandler, partId: " + index);

            viewer.registerSlide(index, image);
        }

        private function imageLoader_progressHandler(event:Event):void
        {
            DebugWrapper.log("INFO: imageLoader_progressHandler");
            //TODO: add loading cursor
        }

        private function imageLoader_completeHandler(event:Event):void
        {
            DebugWrapper.log("INFO: imageLoader_completeHandler");
            //TODO: remove loading cursor
        }

    }
}

